import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@liaoliaots/nestjs-redis';
import { Redis as RedisClient } from 'ioredis';

@Injectable()
export class WalletService {
  constructor(@InjectRedis() private readonly redis: RedisClient) {}

  async getWallets(address: string): Promise<any[]> {
    const pattern = `*${address}*`;
    const keys = await this.scanKeys(pattern);

    const wallets = await Promise.all(
      keys.map(async (key) => {
        const data = await this.redis.hgetall(key);
        return {
          address: key,
          data: this.formatData(data),
        };
      }),
    );
    return wallets;
  }
  private formatData(data: { [key: string]: string }): any {
    const formattedData = {};
    for (const [key, value] of Object.entries(data)) {
      formattedData[key] = value;
    }
    return formattedData;
  }

  async getAllWallets(): Promise<string[]> {
    return await this.scanKeys('*');
  }

  private async scanKeys(pattern: string): Promise<string[]> {
    let cursor = '0';
    let keys: string[] = [];

    do {
      const result = await this.redis.scan(cursor, 'MATCH', pattern);
      cursor = result[0];
      keys = keys.concat(result[1]);
    } while (cursor !== '0');

    return keys;
  }
}
